import { defineStore } from 'pinia';

export const useCartStore = defineStore('cart', {
    state: () => ({
        items: JSON.parse(localStorage.getItem('cartItems')) || [], // 初始化时从 localStorage 恢复数据
    }),
    getters: {
        totalPrice: (state) => {
            console.log('计算总价');
            return state.items.reduce((total, item) => {
                return total + item.price * item.quantity;
            }, 0);
        },
    },
    actions: {
        addItem(item) {
            const existingItem = this.items.find((i) => i.id === item.id);
            if (existingItem) {
                existingItem.quantity += item.quantity;
            } else {
                this.items.push(item);
            }
            this.saveToLocalStorage(); // 保存到 localStorage
        },
        removeItem(id) {
            const index = this.items.findIndex((i) => i.id === id);
            if (index > -1) {
                this.items.splice(index, 1);
            }
            this.saveToLocalStorage(); // 保存到 localStorage
        },
        updateItemQuantity(id, quantity) {
            const item = this.items.find((i) => i.id === id);
            if (item) {
                console.log('修改数量');
                item.quantity = quantity;
            }
            this.saveToLocalStorage(); // 保存到 localStorage
        },
        saveToLocalStorage() {
            localStorage.setItem('cartItems', JSON.stringify(this.items)); // 保存到 localStorage
        },
        clearCart() {
            this.items = []; // 清空购物车
            this.saveToLocalStorage(); // 同步清空 localStorage
        },
    },
});
